package cn.js.sangu.unitStore.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.util.StrUtil;
import cn.js.sangu.unitStore.common.LogType;
import cn.js.sangu.unitStore.common.MyAuthAccess;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.entity.Audit;
import cn.js.sangu.unitStore.entity.ExeApp;
import cn.js.sangu.unitStore.service.AuditService;
import cn.js.sangu.unitStore.service.UserService;
import lombok.extern.slf4j.Slf4j;

/**
 * 说明：ExeApp接口
 * 作者：linshuo
 * 日期：2025/9/9 13:47
 */
// @CrossOrigin //已有全局跨域设置CorsConfig
@Slf4j
@RequestMapping("exeapp")
@RestController
public class ExeAppController {

    /**
     * ExeApp客户端数据请求DTO
     */
    public static class ExeAppDataRequest {
        private String userId;
        private String hardware;
        private String timestamp;

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getHardware() {
            return hardware;
        }

        public void setHardware(String hardware) {
            this.hardware = hardware;
        }

        public String getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(String timestamp) {
            this.timestamp = timestamp;
        }
    }

    static final String OPERATION_AUDIT = "审批记录";

    @Autowired
    AuditService auditService;

    @Autowired
    UserService userService;

    @MyLogsAOP(operation = "ExeApp客户端数据提交", operaType = LogType.ADD)
    @PostMapping("handler")
    public R handler(@RequestBody ExeAppDataRequest request) {
        try {
            // 参数验证
            if (request == null) {
                return R.fail("请求数据不能为空");
            }
            if (StrUtil.isBlank(request.getUserId())) {
                return R.fail("用户ID不能为空");
            }
            if (StrUtil.isBlank(request.getHardware())) {
                return R.fail("硬件信息不能为空");
            }
            if (StrUtil.isBlank(request.getTimestamp())) {
                return R.fail("时间戳不能为空");
            }

            // 创建审计记录
            ExeApp eApp = new ExeApp();
            eApp.setUserId(request.getUserId());
            eApp.setHardware("ExeApp客户端提交数据 - 硬件信息: " + request.getHardware());
            eApp.setTimestamp("客户端时间戳: " + request.getTimestamp());

            log.info(eApp.toString());
            return R.ok(eApp);
        } catch (Exception e) {
            log.error("ExeApp客户端数据提交异常", e);
            return R.fail("数据提交异常: " + e.getMessage());
        }
    }

    // 支持URL参数的旧版本接口（向后兼容）
    @MyLogsAOP(operation = "ExeApp客户端数据提交(兼容版)", operaType = LogType.ADD)
    @PostMapping("handler/legacy")
    public R handlerLegacy(@RequestParam String userId,
            @RequestParam String hardware,
            @RequestParam String timestamp) {
        ExeAppDataRequest request = new ExeAppDataRequest();
        request.setUserId(userId);
        request.setHardware(hardware);
        request.setTimestamp(timestamp);
        return handler(request);
    }

    @MyLogsAOP(operation = OPERATION_AUDIT, operaType = LogType.LOOKUP)
    @GetMapping("findByPage")
    public R findByPage(@RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam String auditName,
            @RequestParam String creator,
            @RequestParam String recipient) {
        QueryWrapper<Audit> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(auditName), "audit_name", auditName);
        wrapper.eq(StrUtil.isNotBlank(creator), "creator", creator);
        wrapper.like(StrUtil.isNotBlank(recipient), "recipient", recipient);
        wrapper.orderByDesc("id");
        // 构建page对象
        Page<Audit> param = new Page<>(pageNum, pageSize);
        Page<Audit> res = auditService.page(param, wrapper);
        return R.ok(res.setRecords(suppleName(res.getRecords())));
    }

    @MyLogsAOP(operation = OPERATION_AUDIT, operaType = LogType.ADD)
    @RequestMapping("save")
    public R save(@RequestBody Audit dto) {
        auditService.saveInfo(dto);
        return R.ok("保存成功");
    }

    @MyLogsAOP(operation = OPERATION_AUDIT, operaType = LogType.DELETE)
    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable Integer id) {
        auditService.removeById(id);
        return R.ok("删除成功");
    }

    @MyLogsAOP(operation = OPERATION_AUDIT, operaType = LogType.BATCH_DELETE)
    @DeleteMapping("deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        auditService.removeBatchByIds(ids);
        return R.ok("批量删除成功");
    }

    // @MyLogsAOP(operation = OPERATION_AUDITUMENT,operaType = LogType.LOOKUP)
    @MyAuthAccess
    @GetMapping("findByBindId/{bindId}")
    public R findById(@PathVariable String bindId) {
        QueryWrapper<Audit> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(bindId), "bind_id", bindId);
        List<Audit> list = auditService.list(wrapper);

        // for ()

        // 建议保存时保存用户名，这里就不用频繁查询了。
        // User user = userService.getById(audit.getCreator());
        // if (null != user){
        // audit.setCreatorName(user.getName());
        // }
        // return R.ok(audit);
        return null;
    }

    // @MyLogsAOP(operation = OPERATION_AUDITUMENT,operaType = LogType.LOOKUP)
    @GetMapping("findByRecent")
    public R findByRecent() {
        LambdaQueryWrapper<Audit> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(Audit::getCreatTime).last("LIMIT 10");
        return R.ok(suppleName(auditService.list(wrapper)));
    }

    /**
     * 补充创建人+修改人+接收人 名称
     * 
     * @param list
     * @return
     */
    private List<Audit> suppleName(List<Audit> list) {
        // for (Audit audit : list) {
        // //创建人
        // User author = userService.getById(audit.getCreator());
        // if (null != author) audit.setCreatorName(author.getName());
        // //修改人
        // User modifier = userService.getById(audit.getModifier());
        // if (null != modifier) audit.setModifierName(modifier.getName());
        // //接收人
        // User recipient = userService.getById(audit.getRecipient());
        // if (null != recipient) audit.setRecipientName(recipient.getName());
        // //接收人
        // User auditor = userService.getById(audit.getAuditor());
        // if (null != auditor) audit.setAuditorName(auditor.getName());
        // }
        // return list;
        return null;
    }

}
